﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace LoveNote.Core.Helpers
{
    /// <summary>
    /// Aes加密
    /// </summary>
    public class AesEncryptUtils
    {
        //字符串转字节数组
        private static byte[] StringToBytes(string str, int length)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            Array.Resize(ref bytes, length);
            return bytes;
        }

        //字节数组转字符串
        private static string BytesToString(byte[] bytes)
        {
            string str = Encoding.UTF8.GetString(bytes);
            return str;
        }

        //加密-String转String
        public static string Encrypt(string str, string key, string iv)
        {
            return Convert.ToBase64String(Encrypt(StringToBytes(str, str.Length + 4), key, iv));//注意长度+4
        }

        //加密-Bytes转Bytes
        public static byte[] Encrypt(byte[] bytes, string key, string iv)
        {
            using (Aes aes = Aes.Create())
            {
                aes.Key = StringToBytes(key, 32);
                aes.IV = StringToBytes(iv, 16);

                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
                byte[] encryptedBytes;

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        csEncrypt.Write(bytes, 0, bytes.Length);
                    }
                    encryptedBytes = msEncrypt.ToArray();
                }
                return encryptedBytes;
            }
        }

        //解密-String转String
        public static string Decrypt(string str, string key, string iv)
        {
            return BytesToString(Decrypt(Convert.FromBase64String(str), key, iv));
        }

        //解密-Bytes转Bytes
        public static byte[] Decrypt(byte[] bytes, string key, string iv)
        {
            using (Aes aes = Aes.Create())
            {
                aes.Key = StringToBytes(key, 32);
                aes.IV = StringToBytes(iv, 16);

                ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

                using (MemoryStream msDecrypt = new MemoryStream(bytes))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (MemoryStream msOutput = new MemoryStream())
                        {
                            csDecrypt.CopyTo(msOutput);
                            return msOutput.ToArray();
                        }
                    }
                }
            }
        }
    }
}
